package channelStatus

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEnv"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisService"
)

func UpdateOpenStatus(channelName string, isOpen bool) error {
	// 查找channel实体
	channelEntity := commRedisService.GetChannelEntity(channelName, commEnv.Service.ModelName)
	if channelEntity == nil {
		return nil
	}

	entity := commEntity.Type.ChannelStatusEntity.Instance()
	entity.ChannelName = channelEntity.ChannelName
	entity.ChannelType = channelEntity.ChannelType

	// 查找状态实体
	exist, err := commRedisService.GetEntityByServiceKey(entity.Type(), entity.MakeServiceKey())
	if err != nil {
		return err
	}

	if exist != nil {
		existEntity := exist.(*commEntity.ChannelStatusEntity)
		existEntity.Open = isOpen
		commRedisService.UpdateEntity(exist)
		return nil
	}

	entity.BaseEntity.Id = channelEntity.BaseEntity.Id
	entity.BaseEntity.CreateTime = channelEntity.BaseEntity.UpdateTime
	entity.BaseEntity.UpdateTime = channelEntity.BaseEntity.UpdateTime
	entity.Open = isOpen

	commRedisService.InsertEntity(entity)

	return nil
}

func UpdateParamStatus(channelName string, key string, value interface{}) error {
	entity := commEntity.Type.ChannelStatusEntity.Instance()
	entity.ChannelName = channelName
	entity.ChannelType = commEnv.Service.ModelName

	// 查找状态实体
	exist, err := commRedisService.GetEntityByServiceKey(entity.Type(), entity.MakeServiceKey())
	if err != nil {
		return err
	}
	if exist == nil {
		return nil
	}


	// 更新信息到redis
	existEntity := exist.(*commEntity.ChannelStatusEntity)
	existEntity.ChannelParam[key] = value
	commRedisService.UpdateEntity(exist)
	return nil
}
